package br.com.tiespec.web.Validator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import br.com.tiespec.web.Util.MsgUtil;

public class ValidatorCPF implements Validator {

	private final int[] pesoCPF = {11, 10, 9, 8, 7, 6, 5, 4, 3, 2};

	private int calcularDigito(String str, int[] peso) {
		int soma = 0;
		for (int indice=str.length()-1, digito; indice >= 0; indice-- ) {
			digito = Integer.parseInt(str.substring(indice,indice+1));
			soma += digito*peso[peso.length-str.length()+indice];
		}
		soma = 11 - soma % 11;
		return soma > 9 ? 0 : soma;
	}

	public boolean isValidCPF(String cpf) {
		if ((cpf==null) || (cpf.length()!=11)) return false;

		Integer digito1 = calcularDigito(cpf.substring(0,9), pesoCPF);
		Integer digito2 = calcularDigito(cpf.substring(0,9) + digito1, pesoCPF);
		return cpf.equals(cpf.substring(0,9) + digito1.toString() + digito2.toString());
	}
	
	@Override
	public void validate(FacesContext context, UIComponent toValidate, Object value)
			throws ValidatorException {
		String cpf = (String) value;
		cpf = cpf.replace(".", "");
		cpf = cpf.replace("-", "");
	    if (!isValidCPF(cpf)){
	    	((UIInput)toValidate).setValid(false);
	        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,MsgUtil.getMensagem("ValidateCPF"), "");  
	        context.addMessage(toValidate.getClientId(context), message);  
	    }
		
	}

}